//
//  SubProductManagerViewController.m
//  LazyCat
//
//  Created by jike on 16/9/30.
//  Copyright © 2016年 zhanshu. All rights reserved.
//

#import "SubProductManagerViewController.h"
#import "MJChiBaoZiHeader.h"
#import "MJChiBaoZiFooter.h"
#import "ProductCell.h"
#import "WebViewController.h"
#import "EditButton.h"
#import "FeWifiManHub.h"
#import "ProductManagerVC.h"
#import "TriangleView.h"

#import "TabButton.h"
#import "proDetialViewController.h" //商品详情
#import "AddProductViewController.h"

#define triangleViewWith   12
#define triangleViewHeight 5

@interface SubProductManagerViewController ()<UIAlertViewDelegate,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray * _dataArray;
    UIView *_backTView;//没订单时背部提醒
    NSString * _urlIndex;//起始页
    BOOL _isLoading;
    NSString *_totalCount;//总页数
    NSDictionary *dataDic;
    NSString *_moneyStr;//成本全局变量
    NSString *_proID;//产品ID
    NSString *_isHot;//是否为推荐
    UITextField *_textField1;//编辑库存
    UIView *popView;
    UIView *_timeView;//库存编辑view
    int _keyH;//键盘高度
    NSString *_proName;//名字
    NSString *_proImg;
    NSIndexPath *_indexPath;//编辑库存刷新指定一行
    FeWifiManHub *_loading;
    NSString *_str;
    NSString *_kuncunNum;//修改的库存数
    NSString *_kuncunNumStr;//修改后库存数
    BOOL _isChangedKunCun;//是否改变了库存
    NSString *_CBStr;//成本
    NSString *_shoujiaStr;//售价
    BOOL _isMoneyChanged;//是否改变了售价
    NSArray *_editArr;//改变的数据源
    NSString *_backFromDetail; // 是否从详情返回，default:NO
    
}
@property (strong, nonatomic)UIView *MenuView;
@property (nonatomic,assign) BOOL flag;
@property (nonatomic,strong)UITableView *tableView;

// triangleView
@property(nonatomic, strong)TriangleView *triangleView;

@end

@implementation SubProductManagerViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    if ([AppData share].isLoadd == YES && ![_backFromDetail isEqualToString:@"Y"])
    {
        _urlIndex = @"1";
        [self loadData:nil];
        [AppData share].isLoadd = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.flag = NO;
    _backFromDetail = @"N";
    [self registerNotifications];
    [self createUI];
    [self loadData:nil];
    [AppData share].isLoadd = NO;
    self.tableView.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(addRefresh)];
}

- (void)createUI {
    self.view.backgroundColor = BackColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    if ([self.isSearchVC isEqualToString:@"YES"]) {
        [self initNav:@"搜索结果" doBack:YES];
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) style:UITableViewStylePlain];
        UIView *lineView2 = [[UIView alloc]initWithFrame:CGRectMake(0, 63.9, ScreenWidth, 0.1)];
        lineView2.backgroundColor = SetColor(1, 1, 1, 0.2);
        [self.navBar addSubview:lineView2];
    }else {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 108 -35) style:UITableViewStylePlain];
    }
    self.tableView.delegate   = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    //add tapGesture to hide the edit menu view;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapedHideMenuView)];
    [self.tableView addGestureRecognizer:tapGestureRecognizer];
    
    _backTView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    _backTView.backgroundColor = BackColor;
    _backTView.hidden = YES;
    [self.tableView addSubview:_backTView];
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 80)/2, 100, 80, 90)];
    backImage.image = [UIImage imageNamed:@"chanpin-no"];
    [_backTView addSubview:backImage];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake((ScreenWidth - 200)/2, backImage.frame.origin.y + 90, 200, 50)];
    label.textColor = SetColor(153, 153, 153, 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"抱歉,您暂时还没有产品";
    [_backTView addSubview:label];
    _urlIndex = @"1";
    _loading = [[FeWifiManHub alloc] initWithView:self.tableView withMode:FeWifiManHubModeOnlyLoader];
    _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y - 104, _loading.frame.size.width, _loading.frame.size.height);
    [self.tableView addSubview:_loading];
    [_loading show];
    _dataArray = [[NSMutableArray alloc]init];
    _isLoading = NO;
    MJRefreshAutoFooter *foot = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    self.tableView.footer = foot;
    _isChangedKunCun = NO;
    _isMoneyChanged = NO;
}

- (void)loadData:(NSIndexPath *)indexPath {
    NSString *kUrl;
    NSLog(@"%ld",self.currentPage);
    if ([self.isSearchVC isEqualToString:@"YES"])
    {
        kUrl = [NSString stringWithFormat:productManagerUrl,@"15",_urlIndex,[AppData share].username,@"",[AppData share].username,self.isHotVC,[self.isSearchVC isEqualToString:@"YES"] ? self.keyWord : @""];
    }else {
        if(self.currentPage == 0){
            kUrl = [NSString stringWithFormat:productManagerUrl,@"15",_urlIndex,[AppData share].username,@"1",[AppData share].username,self.isHotVC,[self.isSearchVC isEqualToString:@"YES"] ? self.keyWord : @""];
        }else if(self.currentPage == 1){
            kUrl = [NSString stringWithFormat:productManagerUrl,@"15",_urlIndex,[AppData share].username,@"0",[AppData share].username,self.isHotVC,[self.isSearchVC isEqualToString:@"YES"] ? self.keyWord : @""];
        }
    }
    
    if ([_urlIndex isEqualToString:@"1"]) {
        [_dataArray removeAllObjects];
    }
    [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        _totalCount = [dic objectForKey:@"totalpage"];
        NSArray *arr = [dic objectForKey:@"products"];
        _editArr = arr;
        [_dataArray addObjectsFromArray:arr];
        _isLoading = NO;
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        if ([_totalCount isEqualToString:@"0"] || _totalCount == nil) {
            _backTView.hidden = NO;
        }else {
            _backTView.hidden = YES;
        }
        [_loading dismiss];
        [_loading removeFromSuperview];
        [self.tableView reloadData];
    }];
    if (kNetworkNotReachability) {
        [_loading dismiss];
        [_loading removeFromSuperview];
    }
}

#pragma mark -- BackRefresh
- (void)registerNotifications
{
    // 刷新通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshNotification:) name:LC_productManager_refresh object:nil];
}

- (void)refreshNotification:(NSNotification *)notification
{
    NSDictionary *infoDic = (NSDictionary *)notification.object;
    NSString *ispublic = infoDic[@"ispublic"];
    NSString *ishot = infoDic[@"ishot"];
    NSString *isdelete = infoDic[@"isdelete"];
    NSInteger pageIndex = [infoDic[@"pageIndex"] integerValue];
    NSString *isSearchVC = infoDic[@"isSearchVC"];
    
    if ([isSearchVC isEqualToString:@"YES"])
    {
        [self loadDataaaa:nil];
        [AppData share].isLoadd = YES;//改变刷新
        
    }else
    {
        // 两个界面通知同时存在，规避开
        if (self.currentPage == pageIndex)
        {
            NSString *currentIsPub = self.currentPage == 0 ? @"1" : @"0";
            
            // delete
            if ([isdelete isEqualToString:@"YES"])
            {
                
                if (_indexPath.row < [_dataArray count])
                {
                    [_dataArray removeObjectAtIndex:_indexPath.row];
                    [self.tableView reloadData];
                    if (_dataArray.count == 0)
                    {
                        _backTView.hidden = NO;
                    }else {
                        _backTView.hidden = YES;
                    }
                    _backFromDetail = @"Y";
                    [AppData share].isLoadd = YES;
                }
                return;
            }
            
            // 上下架
            if (![ispublic isEqualToString:currentIsPub])
            {
                if (_indexPath.row < [_dataArray count])
                {
                    [_dataArray removeObjectAtIndex:_indexPath.row];
                    [self.tableView reloadData];
                    if (_dataArray.count == 0)
                    {
                        _backTView.hidden = NO;
                    }else {
                        _backTView.hidden = YES;
                    }
                }
                _backFromDetail = @"Y";
                [AppData share].isLoadd = YES;
                
            }
            
            // 推荐
            if (_indexPath.row < [_dataArray count]) {
                NSDictionary *dic = _dataArray[_indexPath.row];
                NSMutableDictionary *midDic = [NSMutableDictionary dictionaryWithDictionary:dic];
                [midDic setValue:[NSString stringWithFormat:@"%@",ishot] forKey:@"ishot"];
                [_dataArray replaceObjectAtIndex:_indexPath.row withObject:midDic];
            }
        }
    }
}

//*----------/////
- (void)loadDataaaa:(NSIndexPath *)indexPath {
    NSString *kUrl;
    NSString *numCount;//数据量
    NSInteger count = ([_urlIndex integerValue] - 1) * 15 +_editArr.count;//数据量
    numCount = [NSString stringWithFormat:@"%ld",count];
    
    if ([self.isSearchVC isEqualToString:@"YES"])
    {
        kUrl = [NSString stringWithFormat:productManagerUrl,numCount,@"1",[AppData share].username,@"",[AppData share].username,self.isHotVC,[self.isSearchVC isEqualToString:@"YES"] ? self.keyWord : @""];
    }else
    {
        if(self.currentPage == 0){
            kUrl = [NSString stringWithFormat:productManagerUrl,numCount,@"1",[AppData share].username,@"1",[AppData share].username,self.isHotVC,[self.isSearchVC isEqualToString:@"YES"] ? self.keyWord : @""];
        }else if(self.currentPage == 1){
            kUrl = [NSString stringWithFormat:productManagerUrl,numCount,@"1",[AppData share].username,@"0",[AppData share].username,self.isHotVC,[self.isSearchVC isEqualToString:@"YES"] ? self.keyWord : @""];
        }
    }
    
    [_dataArray removeAllObjects];
    [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        _totalCount = [dic objectForKey:@"totalpage"];
        NSArray *arr = [dic objectForKey:@"products"];
        [_dataArray addObjectsFromArray:arr];
        [self.tableView reloadData];
    }];
}
- (void)addRefresh {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    _urlIndex = @"1";
    [self loadData:nil];
    [self.tableView.header endRefreshing];
}
- (void)loadMore {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    if ([_urlIndex integerValue] >= [_totalCount integerValue]) {
        [[MessShowView share]showWithMess:@"没有更多数据"];
        return ;
    }else{
        _urlIndex = [NSString stringWithFormat:@"%ld",[_urlIndex integerValue]+1];
        [self loadData:nil];
    }
}

-(void)mengBan {
    [UIView animateWithDuration:0.2 animations:^{
        popView.alpha=1;
        _timeView.frame = CGRectMake(0, ScreenHeight - 150, ScreenWidth, 150);
    }];
}
-(void)hidentPopView {
    CGPoint center = _timeView.center;
    center.y = ScreenHeight+75;
    [UIView animateWithDuration:0.2 animations:^{
        //设置要被动画的那个视图
        //在动画结束时，它的属性处于什么状态
        _timeView.center = center;
        popView.alpha = 0;
    }];
    _textField1.text = nil;//隐藏view时将textfield内容置为空。
    [_textField1 resignFirstResponder];
}

#pragma mark -- cell上按钮点击方法
- (void)btnClick:(UIButton *)sender event:(id)event {
    //取indexpath
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath= [self.tableView indexPathForRowAtPoint:currentTouchPosition];
    _indexPath = indexPath;
#pragma mark -- menu..编辑菜单
    if (sender.tag == 1114){//编辑菜单menu
//        ProductCell *cell = (ProductCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        
        CGRect rect = [self.tableView rectForRowAtIndexPath:indexPath];
        
        CGFloat absoluteY = rect.origin.y - [self.tableView contentOffset].y + 110 + 150;
        
        CGFloat startY = rect.origin.y + 108;
        CGFloat triangleY = startY - triangleViewHeight;
        BOOL isDirectionUp = YES;
        if (absoluteY > self.tableView.frame.size.height ) {
            startY = rect.origin.y + 110 - 40 -150;
            triangleY = startY + 150;
            isDirectionUp = NO;
        }
        
        [self setUpMenuViewWithFrame:CGRectMake(ScreenWidth - 140, startY, 130, 150)];

        [self setupTriangleViewWithFrame:CGRectMake(ScreenWidth - 33 - triangleViewWith/2.0, triangleY, triangleViewWith,triangleViewHeight) withTransformDirect:isDirectionUp];
        
        if (self.flag) {
            self.MenuView.hidden = YES;
            self.triangleView.hidden = YES;
            self.flag = NO;
        }else{
            [self refreshMenuView:indexPath];
            self.MenuView.hidden = NO;
            self.triangleView.hidden = NO;
            self.flag = YES;
        }
        
    }else if (sender.tag == 2016){//库存编辑按钮----
        ProductCell *cell = (ProductCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        _kuncunNumStr = cell.kuCunLabel.text;
        NSLog(@"%@",_kuncunNumStr);
        if (indexPath.row < [_dataArray count]) {
            _proID = [_dataArray[indexPath.row]objectForKey:@"userproductid"];
        }
        _indexPath = indexPath;
        [self.view endEditing:YES];
        cell.baoCunBtn.hidden = YES;
        [self mengBan];//显示库存编辑view
    }else if (sender.tag == 6666){//进入详情
        if (kNetworkNotReachability) { // 没网
            [[MessShowView share] showWithMess:@"当前网络不给力"];
            return;
        }else { //2016-09-28,跳转用block
            if (_indexPath.row < [_dataArray count]) {
                _proID = [_dataArray[_indexPath.row]objectForKey:@"productid"];
                _proName = [_dataArray[_indexPath.row]objectForKey:@"productname"];
                proDetialViewController *proDetailVC = [[proDetialViewController alloc]init];
                proDetailVC.pId = _proID;
                proDetailVC.pTitle = _proName;
                proDetailVC.CPage = self.currentPage;
                proDetailVC.isSearchVC = self.isSearchVC;
                
                if ([self.isSearchVC isEqualToString:@"YES"])
                { // 搜索界面跳转
                    [self.navigationController pushViewController:proDetailVC animated:YES];
                }else
                { // 普通界面跳转
                    if (_myBlock) {//跳转页面
                        _myBlock(proDetailVC);
                    }
                }
            }
        }
    }
}

- (void)refreshMenuView:(NSIndexPath *)indexPath;
{  // 70,71,72,73,74
    TabButton *recommendBtn = (TabButton *)[self.tableView viewWithTag:72];
    NSString *ishot;
    
    if (indexPath.row < _dataArray.count) {
        ishot = [_dataArray[indexPath.row] objectForKey:@"ishot"];
        if ([ishot isEqualToString:@"1"]) {
            recommendBtn.selected = YES;
        }else {
            recommendBtn.selected = NO;
        }
    }
}

// 分享
-(void)fenXiangAction {
    NSString *url = [NSString stringWithFormat:@"%@/LCat/Product-%@?appname=lanmao&plat=ios&username=%@&iszhanggui=1&sign2=%@",BaseUrl,_proID,[AppData share].username,[Utils md5SignStr]];
    [[ShareView share] showMess:[NSString stringWithFormat:@"%@%@",_proName,url] withImgUrl:_proImg url:url];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"productcell"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"ProductCell" owner:nil options:nil][0];
    }
    [cell.baoCunBtn addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.inBtnClicl addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];//进入详情按钮
    [cell.inBtnClick2 addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];//进入详情按钮
    cell.backgroundColor = BackColor;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //产品数组
    if (indexPath.row < [_dataArray count]) {////////防止数组越界
        cell.titleLabel.text = [_dataArray[indexPath.row]objectForKey:@"productname"];
        cell.kuCunLabel.text = [NSString stringWithFormat:@"%@",[_dataArray[indexPath.row]objectForKey:@"totalnumstock"]];//库存
        cell.kuCunLabel.adjustsFontSizeToFitWidth = YES;
        cell.shouJiaTextF.text = [NSString stringWithFormat:@"¥%@",[_dataArray[indexPath.row]objectForKey:@"minsaleprice"]];//价格
        //售价输入框
        cell.shouJiaTextF.textColor = MainColor;
        cell.shouJiaTextF.font = [UIFont systemFontOfSize:17];
        cell.shouJiaTextF.tag = 2222;
        cell.shouJiaTextF.autocorrectionType = UITextAutocorrectionTypeNo;
        
        cell.shouJiaTextF.delegate = self;
        cell.shouJiaTextF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        //成本价输入框
        cell.chengBenTextF.text = [_dataArray[indexPath.row]objectForKey:@"mincostprice"];
        cell.chengBenTextF.font = [UIFont systemFontOfSize:12];
        [cell.iconImage sd_setImageWithURL:[NSURL URLWithString:[_dataArray[indexPath.row]objectForKey:@"mainimage"]] placeholderImage:[UIImage imageNamed:@"product-no-pic"]];
        cell.chengBenTextF.adjustsFontSizeToFitWidth = YES;
        cell.chengBenTextF.delegate = self;
        cell.chengBenTextF.tag = 2223;
        cell.chengBenTextF.autocorrectionType = UITextAutocorrectionTypeNo;
        cell.chengBenTextF.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        [cell.chengBenTextF setValue:[UIFont boldSystemFontOfSize:11] forKeyPath:@"_placeholderLabel.font"];
        
        // 多规格  property specname
        NSString *tagTitle = [_dataArray[indexPath.row]objectForKey:@"title"];
        if (tagTitle.length != 0) {
            cell.tagTitle.hidden = NO;
        }else {
            cell.tagTitle.hidden = YES;
        }
        cell.guigeLabel.text = [_dataArray[indexPath.row]objectForKey:@"specname"];
        
    }
    
    [cell.subviews[0] setBackgroundColor:[UIColor clearColor]];
    [cell setNeedsDisplay];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 110;
}

#pragma mark -- BtnClick ..
- (void)tapedHideMenuView
{
    self.MenuView.hidden = YES;
    self.flag = NO;
}

#pragma mark -- 创建菜单menuView
- (void)setUpMenuViewWithFrame:(CGRect)frame
{  /**
     *  创建menu
     */
    NSString *ispublic;
    if (_indexPath.row < [_dataArray count]) {
        ispublic = [_dataArray[_indexPath.row] objectForKey:@"ispublic"];
    }
    
    if (!self.MenuView) {
        self.MenuView = [[UIView alloc]initWithFrame:frame];
        self.MenuView.backgroundColor = [UIColor whiteColor];
        self.MenuView.layer.shadowOffset = CGSizeMake(0, 0);
        self.MenuView.layer.shadowColor = [UIColor grayColor].CGColor;
        self.MenuView.layer.shadowOpacity = 0.5;
        self.MenuView.layer.shadowRadius = 5;
        [self.tableView addSubview:self.MenuView];
        
        NSString *upDownTitleStr;
        NSString *upDownImageStr;
        if ([ispublic isEqualToString:@"1"])
        {
            upDownTitleStr = @"下架";
            upDownImageStr = @"xiajia_icon";
        }else if ([ispublic isEqualToString:@"0"])
        {
            upDownTitleStr = @"上架";
            upDownImageStr = @"shangjia_icon";
        }
        
        
        NSArray *titleArr = @[@"编辑",upDownTitleStr,@"推荐",@"分享",@"删除"];
        NSArray *seleTitleArr = @[@"编辑",upDownTitleStr,@"已推荐",@"分享",@"删除"];
        NSArray *imageArr     = @[@"bianji_icon",
                                  upDownImageStr,
                                  @"tuijian_icon",
                                  @"fenxiang_icon",
                                  @"shanchu_icon"];
        
        NSArray *seleImageArr = @[@"bianji_icon",
                                  upDownImageStr,
                                  @"tuijian_org_icon",
                                  @"fenxiang_icon",
                                  @"shanchu_icon"];
        
        for (int i = 0; i < 5; i++) {
            TabButton *btn = [[TabButton alloc] init];
            btn.frame = CGRectMake(0, i * 30, 130, 30);
            [btn setTitle:titleArr[i] forState:UIControlStateNormal];
            [btn setTitle:seleTitleArr[i] forState:UIControlStateSelected];
            [btn setTitleColor:SetColor(51, 51, 51, 1) forState:UIControlStateNormal];
            btn.titleLabel.font = FontSet(13);
            [btn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:seleImageArr[i]] forState:UIControlStateSelected];
            btn.tag = 70 + i;
            [btn addTarget:self action:@selector(menuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
            [self.MenuView addSubview:btn];
        }
    }
    
    TabButton *onOrDownBtn  = (TabButton *)[self.tableView viewWithTag:71];
    if ([ispublic isEqualToString:@"0"])
    {
        [onOrDownBtn setTitle:@"上架" forState:UIControlStateNormal];
    }else if ([ispublic isEqualToString:@"1"])
    {
        [onOrDownBtn setTitle:@"下架" forState:UIControlStateNormal];
    }

    self.MenuView.frame = frame;
}
#pragma mark 绘制三角形
- (void)setupTriangleViewWithFrame:(CGRect)frame withTransformDirect:(BOOL)isDirectionUp
{
    if (!_triangleView) {
        _triangleView = [[TriangleView alloc] initWithFrame:CGRectMake(frame.origin.x, frame.origin.y, triangleViewWith, triangleViewHeight)];
        [self.tableView addSubview:_triangleView];
    }
    
    // change the direction of the triangleView
    if (isDirectionUp) {
        self.triangleView.transform = CGAffineTransformMakeRotation(0);
    }else {
        self.triangleView.transform = CGAffineTransformMakeRotation(M_PI);
    }
    
    // refrsh the frame of view when View will appear
    self.triangleView.frame = frame;
    
}

#pragma mark --MenuBtnClick..
- (void)menuBtnClick:(TabButton *)sender
{
//    TabButton *editBtn      = (TabButton *)[self.tableView viewWithTag:70];
    
    if (_indexPath.row < [_dataArray count]) {
        _proID = [_dataArray[_indexPath.row]objectForKey:@"productid"];
    }
    if (sender.tag == 70) { // 编辑
        [self menuBtnEdit];
    }else if (sender.tag == 71) { // 上下架
        [self menuBtnPutOnSaleOrDown];
    }else if (sender.tag == 72) { // 推荐
        [self menuBtnRecommend];
    }else if (sender.tag == 73) { // 分享
        [self menuBtnShare];
    }else if (sender.tag == 74) { // 删除
        [self menuBtnDelete];
    }
    [self tapedHideMenuView];
    
}
#pragma mark -- MenuBtnFunctions...
- (void)menuBtnEdit
{  // 编辑
    AddProductViewController *addVC = [[AddProductViewController alloc]init];
    addVC.addVCStyle = LCProductStyleEdit;
    addVC.userproductid = _proID;
    
    [addVC setSaveSuccessBlock:^(BOOL isSuccess) {
        if (isSuccess) {
            [AppData share].isLoadd = YES;
        }
    }];
    
    if (self.myBlock) {
        self.myBlock(addVC);
    }else {
        [self.navigationController pushViewController:addVC animated:YES];
    }
}

// 上下架
- (void)menuBtnPutOnSaleOrDown
{
    NSString *kUrl;
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    NSMutableArray *arr = [NSMutableArray array];//产品信息
    NSString *ispublic = [NSString stringWithFormat:@"%@",self.currentPage == 0 ? @"0" : @"1"];
    [arr addObject:_proID];
    [dictionary setValue:arr forKey:@"productids"];
    [dictionary setValue:ispublic forKey:@"ispublic"];
    NSLog(@"%@",dictionary);
    NSError *error = nil;
    //NSJSONWritingPrettyPrinted:指定生成的JSON数据应使用空格旨在使输出更加可读。如果这个选项是没有设置,最紧凑的可能生成JSON表示。
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] > 0 && error == nil){
        NSLog(@"Successfully serialized the dictionary into data.");
        //NSData转换为String
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"JSON String = %@", jsonString);
    }
    else if ([jsonData length] == 0 &&
             error == nil){
        NSLog(@"No data was returned after serialization.");
    }
    else if (error != nil){
        NSLog(@"An error happened = %@", error);
    }
    //post请求
    kUrl = [NSString stringWithFormat:shangXiaJiaProduct,[AppData share].username,[AppData share].username];
    NSLog(@"%@",kUrl);
    NSMutableDictionary *dicc = [NSMutableDictionary dictionary];
    [dicc setObject:dictionary forKey:@"data"];
    NSLog(@"%@",dicc);
    // 手机型号
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *iptype = [userDefaul objectForKey:@"iptype"];
    NSString *banben = [userDefaul objectForKey:@"banben"];
    NSString *temUrl = [NSString stringWithFormat:@"%@&terminal=%@&OSVersion=%@",kUrl,iptype,banben];
    // 判断是否签名
    if([temUrl rangeOfString:@"sign2"].location !=NSNotFound)//_roaldSearchText
    {
        // 存在
    }else{
        // 不存在
        temUrl = [NSString stringWithFormat:@"%@&sign2=%@",temUrl,[Utils md5SignStr]];
        
    }
    NSString *lower = [temUrl lowercaseString];
    if ([lower rangeOfString:@"username"].location !=NSNotFound) {
        // 存在
    }else{
        // 不存在
        temUrl = [NSString stringWithFormat:@"%@&Username=%@",temUrl,[AppData share].username];
    }
    //NSLog(@"1----------%@",temUrl);
    temUrl = [temUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"2----------%@",temUrl);
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSError *error1;
    NSURLResponse *theResponse;
    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:temUrl]];
    NSString *bodyString=[NSString stringWithFormat:@"data=%@",jsonString];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
    [theRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSData *data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&error];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if ([dic[@"r"] isEqualToString:@"T"]) {
        [[MessShowView share]showWithMess:[NSString stringWithFormat:@"%@",self.currentPage == 0 ? @"下架成功" : @"上架成功"]];
        [_dataArray removeObjectAtIndex:_indexPath.row];
        [self.tableView reloadData];
        if (_dataArray.count == 0)
        {
            _backTView.hidden = NO;
        }else {
            _backTView.hidden = YES;
        }
        [AppData share].isLoadd = YES;
    }else {
        [[MessShowView share]showWithMess:dic[@"m"]];
    }
}

// 推荐
- (void)menuBtnRecommend
{
    if (_indexPath.row < [_dataArray count]) {
        _isHot = _dataArray[_indexPath.row][@"ishot"];
    }
    
    NSString *kUrl;
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    NSMutableArray *arr = [NSMutableArray array];//产品信息
    NSString *ishot = [NSString stringWithFormat:@"%@",[_isHot isEqualToString:@"0"] ? @"1" : @"0"];
    [arr addObject:_proID];
    [dictionary setValue:arr forKey:@"productids"];
    [dictionary setValue:ishot forKey:@"ishot"];
    NSLog(@"%@",dictionary);
    NSError *error = nil;
    //NSJSONWritingPrettyPrinted:指定生成的JSON数据应使用空格旨在使输出更加可读。如果这个选项是没有设置,最紧凑的可能生成JSON表示。
    NSData *jsonData = [NSJSONSerialization
                        dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
    if ([jsonData length] > 0 && error == nil){
        NSLog(@"Successfully serialized the dictionary into data.");
        //NSData转换为String
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"JSON String = %@", jsonString);
    }
    else if ([jsonData length] == 0 &&
             error == nil){
        NSLog(@"No data was returned after serialization.");
    }
    else if (error != nil){
        NSLog(@"An error happened = %@", error);
    }
    //post请求
    kUrl = [NSString stringWithFormat:isRecommend,[AppData share].username,[AppData share].username];
    NSMutableDictionary *dicc = [NSMutableDictionary dictionary];
    [dicc setObject:dictionary forKey:@"data"];
    // 手机型号
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *iptype = [userDefaul objectForKey:@"iptype"];
    NSString *banben = [userDefaul objectForKey:@"banben"];
    NSString *temUrl = [NSString stringWithFormat:@"%@&terminal=%@&OSVersion=%@",kUrl,iptype,banben];
    // 判断是否签名
    if([temUrl rangeOfString:@"sign2"].location !=NSNotFound)//_roaldSearchText
    { // 存在
    }else{ // 不存在
        temUrl = [NSString stringWithFormat:@"%@&sign2=%@",temUrl,[Utils md5SignStr]];
    }
    NSString *lower = [temUrl lowercaseString];
    if ([lower rangeOfString:@"username"].location !=NSNotFound) { // 存在
    }else{ // 不存在
        temUrl = [NSString stringWithFormat:@"%@&Username=%@",temUrl,[AppData share].username];
    }
    //NSLog(@"1----------%@",temUrl);
    temUrl = [temUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //NSLog(@"2----------%@",temUrl);
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSError *error1;
    LCLog(@"%@",error1);
    NSURLResponse *theResponse;
    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:temUrl]];
    NSString *bodyString=[NSString stringWithFormat:@"data=%@",jsonString];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
    [theRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    NSData *data = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&error];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if ([dic[@"r"] isEqualToString:@"T"]) {
        [[MessShowView share]showWithMess:[NSString stringWithFormat:@"%@",[_isHot isEqualToString:@"0"] ? @"已推荐" : @"取消推荐"]];
        
        
        // change the result and refresh
        NSDictionary *dic = _dataArray[_indexPath.row];
        NSMutableDictionary *midDic = [NSMutableDictionary dictionaryWithDictionary:dic];
        [midDic setValue:[NSString stringWithFormat:@"%@",[_isHot isEqualToString:@"0"] ? @"1" : @"0"] forKey:@"ishot"];
        [_dataArray replaceObjectAtIndex:_indexPath.row withObject:midDic];
    }else {
        [[MessShowView share]showWithMess:dic[@"m"]];
    }
}

- (void)menuBtnShare
{
    if (_indexPath.row < [_dataArray count]) {
        _proID = [_dataArray[_indexPath.row]objectForKey:@"productid"];
        _proName = [_dataArray[_indexPath.row]objectForKey:@"productname"];
        _proImg = [_dataArray[_indexPath.row]objectForKey:@"mainimage"];
    }
    [self fenXiangAction];
}

- (void)menuBtnDelete
{
    UIAlertView *alertV = [[UIAlertView alloc]initWithTitle:@"确认删除" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
    alertV.tag = 50;
    [alertV show];
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"%ld",buttonIndex);
    if (buttonIndex == 1) {
        NSString *url = [NSString stringWithFormat:deleteProductUrl,[AppData share].username,[AppData share].username,_proID];
        [NTNetUtil sendRequestWithUrl:url requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
            NSDictionary *dic = networkRequest.responseData;
            NSString *result = [dic objectForKey:@"m"];
            if ([result isEqualToString:@"success"]) {
                // 删除..
                [_dataArray removeObjectAtIndex:_indexPath.row];
                [self.tableView reloadData];
                [AppData share].isLoadd = YES;
                
                if (_dataArray.count == 0)
                {
                    _backTView.hidden = NO;
                }else {
                    _backTView.hidden = YES;
                }
                [[MessShowView share]showWithMess:@"商品删除成功" login:YES];
            }else  {
                [[MessShowView share]showWithMess:result login:NO];
            }
        }];
    }else {
        
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:LC_productManager_refresh object:nil];
}
@end
